package com.cn.ycy.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

public class RequestBuildUtil {

  public final static String URL_ENCODING = "UTF-8";

  /**
   * urlencode
   */
  public static String concatQueryString(Map<String, String> parameters) throws UnsupportedEncodingException {
    if (null == parameters) {
      return null;
    }

    StringBuilder urlBuilder = new StringBuilder();
    for (Map.Entry<String, String> entry : parameters.entrySet()) {
      String key = entry.getKey();
      String val = entry.getValue();
      urlBuilder.append(encode(key));
      if (val != null) {
        urlBuilder.append("=").append(encode(val));
      }
      urlBuilder.append("&");
    }

    int strIndex = urlBuilder.length();
    if (parameters.size() > 0) {
      urlBuilder.deleteCharAt(strIndex - 1);
    }

    return urlBuilder.toString();
  }

  public static String encode(String value) throws UnsupportedEncodingException {
    return URLEncoder.encode(value, URL_ENCODING);
  }

}
